/**
 * Created by DevilsEyes on 2016/4/19.
 */
'use strict';

var $course = require('../db/course.js');

let filter = function (o) {
    return {
        _id: o._id,
        title: o.title,//标题

        tags: o.tags || '',//标签  A#B#C#D
        view: o.view || 0,//浏览量
        class: o.class || '',//班级  A#B#C#D

        imgs: o.imgs.map((i)=>JSON.parse(i)),//图片 文件JSON字符串组
        article: o.article || '',//内容(允许换行\n)
        attachments: o.attachments.map((i)=>JSON.parse(i)),//附件 文件JSON字符串组

        updated: o.updated
    }
};

module.exports = {

    getOnebyId(id){
        return new Promise((O, X)=> {
            $course
                .findOneAndUpdate({_id: id}, {$inc: {view: 1}})
                .then((course)=> {
                    if (course) {
                        O(filter(course));
                    } else {
                        X({
                            code: 9999,
                            msg: '未找到该课件'
                        })
                    }
                });
        })
    },
    getList(ClassStr){
        if (ClassStr) {
            return new Promise((O, X)=> {
                $course
                    .where('class', new RegExp(`(^|#)${ClassStr}($|#)`))
                    .then((courses)=> {

                        if (courses) {
                            O(courses);
                        } else {
                            throw {
                                code: 9999,
                                msg: '发生了一些错误'
                            }
                        }

                    });
            })
        } else {
            return new Promise((O, X)=> {
                $course
                    .find()
                    .then((courses)=> {

                        if (courses) {
                            O(courses);
                        } else {
                            throw {
                                code: 9999,
                                msg: '发生了一些错误'
                            }
                        }

                    });
            })
        }

    }

};